#!/usr/bin/pythono

import os
import sys
import subprocess
import traceback

def fork_exec(command, command_line=False):
    try:
        pid = os.fork()
    except OSError, e:
        print >>sys.stderr, 'fatal: fork new process failed! ERROR INFO: ', e.strerror
        traceback.print_exc()

    if 0!=pid:
        #sys.exit( 0 )
        try:
            os.waitpid( pid, 0 )
        except OSError, e:
            print >>sys.stderr, 'fatal: Parent process wait failed. ERROR INFO: ', e.strerror
            traceback.print_exc()
    elif 0==pid:
        #child process
        if True==command_line:
            try:
                if 0==os.system( command ):
                    sys.exit(0)
                else:
                    print >>sys.stderr, 'fatal: exec command %s failed!' %command

            except OSError, e:
                print >>sys.stderr, 'fatal: system failed to exec %s ' %command
                traceback.print_exc()
        else:
            try:
                proc = subprocess.Popen( command, stdin=subprocess.PIPE )
            except OSError, e:
                print >>sys.stderr, 'fatal: thread exec command %s failed!' %command
                traceback.print_exc()

            if 0==proc.wait():
                sys.exit( 0 )
            else:
                print >>sys.stderr, 'fatal: thread wait failed!'
                sys.exit( 0 )
